package cn.com.manager.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.com.manager.dao.DemoMapper;
import cn.com.manager.page.PageInfo;
import cn.com.manager.pojo.Demo;
import cn.com.manager.pojo.DemoExample;
import cn.com.manager.pojo.DemoExample.Criteria;
import cn.com.manager.service.DemoService;

@Service
public class DemoServiceImpl implements DemoService {

	@Autowired
	private DemoMapper demoMapper;

	@Override
	@Transactional(value = "transactionManager", propagation = Propagation.REQUIRED)
	public int save(Demo demo) {
		int result = 0;
		if (demo != null && StringUtils.isNoneBlank(demo.getId())) {
			result = demoMapper.updateByPrimaryKeySelective(demo);
		} else {
			result = demoMapper.insert(demo);
		}
		return result;
	}

	@Override
	public List<Demo> search(Demo demo, PageInfo pageInfo) {
		DemoExample example = new DemoExample();
		if (demo != null) {
			Criteria criteria = example.createCriteria();
			if (StringUtils.isNoneBlank(demo.getTitle())) {
				criteria.andTitleLike("%" + demo.getTitle() + "%");
			}
			if(StringUtils.isNoneBlank(demo.getStatus())){
				criteria.andStatusEqualTo(demo.getStatus());
			}
		}
		if (pageInfo != null) {
			Page<Demo> results = PageHelper.startPage(pageInfo.getPageNo(), pageInfo.getPageSize(), true) .doSelectPage(() -> demoMapper.selectByExample(example));
			pageInfo.setCount((int) results.getTotal());
			return results.getResult();
		} else {
			return demoMapper.selectByExample(example);
		}
	}

	@Override
	public Demo searchById(String id) {
		return demoMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional(value = "transactionManager", propagation = Propagation.REQUIRED)
	public int remove(Demo demo) {
		return demoMapper.deleteByPrimaryKey(demo.getId());
	}

}
